/**
 * 邮件模板新增编辑页
 */
import React from 'react';

import { Button, Card, Form, Input } from 'antd';

import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import { formatResultByFetchDetail, onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import pageTabUtil from '@/utils/pageTabUtil';

import { FilePreviewAndUpload } from '../components';
import { getEntryContractTemplateConfigDetail, saveContractTemplate } from '../services';
import styles from './index.less';

const EntryLaborContractEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator, setFieldsValue } = form;

    const [fileLists, setFileLists] = React.useState([]);
    const [previewUrl, setPreviewUrl] = React.useState('');
    const [formUploading, setFormUploading] = React.useState(false);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('add');
    }, [location]);

    // 获取模板
    const { data, loading } = useRequest(() => getEntryContractTemplateConfigDetail(query.id), {
        ...defaultFormatResult,
        ready: !!query?.id,
        onSuccess: res => {
            setFieldsValue({
                settingName: res?.settingName,
                administrativeScopes: res?.administrativeScopes ? res?.administrativeScopes?.[0] : undefined,
                reqSaveFileRelationDto: res?.resCombineBusinessResourceDtoList || []
            });
            setFileLists(res?.resCombineBusinessResourceDtoList?.[0] || []);
            setPreviewUrl(res?.resCombineBusinessResourceDtoList?.[0]?.url);
        },
        formatResult: formatResultByFetchDetail
    });
    // 保存/提交劳动合同
    const { loading: saveLoading, run: saveTemplate } = useRequest(saveContractTemplate, {
        manual: true,
        onSuccess: onSuccessBySave
    });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            console.log(err, values, 'err, values');
            if (!err) {
                const { reqSaveFileRelationDto, administrativeScopes, ...rest } = values;
                const fileDto = {
                    list: reqSaveFileRelationDto
                };
                const params = {
                    isDefault: data?.isDefault ?? 0,
                    ...rest,
                    reqSaveFileRelationDto: fileDto,
                    administrativeScopes: administrativeScopes ? [administrativeScopes] : []
                };
                if (!isAddPage) {
                    params.id = query?.id;
                }
                saveTemplate(params);
            }
        });
    };

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '添加模板' : '编辑模板'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleSubmit} loading={saveLoading || formUploading}>
                            提交
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="模板名称">
                        {getFieldDecorator('settingName', {
                            // initialValue: data?.templateName || '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入模板名称'
                                }
                            ]
                        })(<Input placeholder="请输入模板名称" allowClear maxLength={200} style={{ maxWidth: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="适用行政机构">
                        {data?.isDefault === 1 && '全集团'}
                        {data?.isDefault === 1 &&
                            form.getFieldDecorator('administrativeScopes', {
                                initialValue: data?.administrativeScopes || undefined
                            })(<input type="hidden" />)}
                        {data?.isDefault !== 1 &&
                            form.getFieldDecorator('administrativeScopes', {
                                initialValue: data?.administrativeScopes || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '适用行政机构不能为空'
                                    }
                                ]
                            })(
                                <OrganizationSelect
                                    style={{ maxWidth: 528 }}
                                    isNeedPermission={false}
                                    onlyCompany
                                    placeholder="请选择行政机构"
                                />
                            )}
                    </Form.Item>

                    <Form.Item label="合同文件" required>
                        <FilePreviewAndUpload
                            setFormUploading={setFormUploading}
                            uploadConfig={{
                                businessCode: 'Contract',
                                categoryCode: 'newContractVersion',
                                checkFileType: 'doc、docx',
                                checkFileTypeMsg: '只能上传doc、docx格式的文件！',
                                checkFileSize: 20,
                                checkFileSizeMsg: '文件大小不能超过20MB！'
                            }}
                            previewUrl={previewUrl}
                            fileLists={fileLists}
                            setFileLists={setFileLists}
                            onPreviewChange={url => {
                                setPreviewUrl(url);
                            }}
                            onChange={value => {
                                // setResourceRelation([value]);
                                setFieldsValue({
                                    reqSaveFileRelationDto: [value]
                                });
                            }}
                            onDelete={() => {
                                // setResourceRelation([]);
                                setFieldsValue({
                                    reqSaveFileRelationDto: undefined
                                });
                                setPreviewUrl('');
                            }}
                        />
                        {getFieldDecorator('reqSaveFileRelationDto', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择劳动合同'
                                }
                            ]
                        })(<div style={{ marginTop: 4 }} />)}
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default React.memo(Form.create()(EntryLaborContractEdit));
